<?php

//necessário para todas as páginas do admin (facilitador)
include("defaultAdmin.php");

class CrudUsuarios {
	private $objUsrSession;
	private $objDaoPrincipal;
	
	private $menu1 = "usuarios";
	private $classe_css = "usuarios";

	private $DAO_principal = "Usuario";
	private $PK = "id_usuario";
	
	private $posGrid = array("Nome", "Usuário");
	private $posArrGrid = array("nome_usuario", "username");
	private $titleGrid = "Usuários";
	private $titleForm = "Usuário";
	private $errosForm = array();
	
	private $camposObrigatorios = array(
		array("nome_usuario", "", "MENS_ERRO_NOME", "Campo Obrigatório."),
		array("usuario_usuario", "", "MENS_ERRO_USERNAME", "Campo Obrigatório."),
		array("email_usuario", "", "MENS_ERRO_EMAIL", "Campo Obrigatório.")
	);
	
	private function setItensRelacionados(){
		global $objCtrlSmarty;
		global $menu;
		
		$add = $list = array();
		$add["title"] = "Adicionar um novo item";
		$add["opcoes"][] = array("texto" => "Usuários", "link" => self::getLinkCadastrar());
		$objCtrlSmarty->assign("ADICIONAR",$add);
		
		$list["title"] = "Listar todos os itens";
		$list["opcoes"][] = array("texto" => "Usuários", "link" => HttpUtil::getLink($menu, "pos1=".__CLASS__));
		$objCtrlSmarty->assign("LISTAR",$list);
	}
	
	private function getFormPadrao($id, $arrCampos = array()){
		global $menu;
		global $objCtrlSmarty;
		
		if(isset($id)){
			if(empty($arrCampos)){
				//busco os dados do banco
				$arrCampos = Utf8Parsers::arrayUtf8Encode(self::getObjDaoPrincipal()->buscaCampos($id));
			}
		}
		
		$arrOptions[] = array("text" => "Administrador Geral", "value" => "A");
		$arrOptions[] = array("text" => "Gerente", "value" => "G");
		$arrOptions[] = array("text" => "Vendedor", "value" => "V");
		
		
		$text[] = array(
					"label" => array("texto" => "Nome", "for" => "nome_usuario"),
					"campo" => array("type" => "text", "name" => "nome_usuario", "value" => $arrCampos["nome_usuario"], "maxlength" => 70),
					"msg_erro" => $this->errosForm["MENS_ERRO_NOME"],
					"obrigatorio" => true
				);
		$text[] = array(
					"label" => array("texto" => "Usuário", "for" => "usuario_usuario"),
					"campo" => array("type" => "text", "name" => "usuario_usuario", "value" => $arrCampos["usuario_usuario"], "maxlength" => 15),
					"msg_erro" => $this->errosForm["MENS_ERRO_USERNAME"],
					"obrigatorio" => true
				);
		$text[] = array(
					"label" => array("texto" => "Email", "for" => "email_usuario"),
					"campo" => array("type" => "text", "name" => "email_usuario", "value" => $arrCampos["email_usuario"], "maxlength" => 70),
					"msg_erro" => $this->errosForm["MENS_ERRO_EMAIL"],
					"obrigatorio" => true
				);
		$password[] = array(
					"label" => array("texto" => "Senha", "for" => "senha_usuario"),
					"campo" => array("type" => "password", "name" => "senha_usuario", "maxlength" => 20),
					"msg_erro" => $this->errosForm["MENS_ERRO_SENHA"],
				);
		$password[] = array(
					"label" => array("texto" => "Confirma Senha", "for" => "confsenha_usuario"),
					"campo" => array("type" => "password", "name" => "confsenha_usuario", "maxlength" => 20),
					"msg_erro" => $this->errosForm["MENS_ERRO_CONF_SENHA"],
				);
		$select[] = array( 
						"label" => array("texto" => "Grupo", "for" => "grupo_usuario"),
						"campo" => array("type" => "select", "name" => "grupo_usuario", "value" => $arrCampos["grupo_usuario"], "valores" => $arrOptions)
					);
		$hidden[] = array(
						"campo" => array("type" => "hidden", "name" => "id_usuario", "value" => $arrCampos["id_usuario"])
					);
		$ordem = array("nome_usuario", "email_usuario", "usuario_usuario", "senha_usuario", "confsenha_usuario");
						
		$camposForm = array("ordem" => $ordem, "text" => $text, "select" => $select, "hidden" => $hidden, "password" => $password);

		//seto no formulário os campos
		$objCtrlSmarty->assign(CAMPOS_FORM,$camposForm);
		$objCtrlSmarty->assign("TITLE", (($id)?"Editar ":"Cadastrar ").$this->titleForm);
		self::setItensRelacionados();
		self::setLinksPadrao();
		$objCtrlSmarty->assign("CONTEUDO_ADMIN",$objCtrlSmarty->fetch(TPLS_FILE."admin/formRegistros.tpl"));
	}
	
	private function verificacoesExtras(){
		if(isset($_POST["id_usuario"]) && is_numeric($_POST["id_usuario"])){
			$arrDados = self::getObjDaoPrincipal()->buscaCampos(getId($_POST["id_usuario"]));
			if($_POST["senha_usuario"]!="" && $_POST["senha_usuario"] == $_POST["confsenha_usuario"])
				$_POST["senha_usuario"] = base64_encode(md5($_POST["senha_usuario"]));
			else if($_POST["senha_usuario"]!="" && ($_POST["senha_usuario"] != $_POST["confsenha_usuario"]))
				$this->errosForm["MENS_ERRO_SENHA"] = "A senha deve ser igual à sua confirmação.";
			else if($_POST["senha_usuario"]=="" && $_POST["confsenha_usuario"]=="")
				$_POST["senha_usuario"] = $arrDados["senha_usuario"];
		}else{
			if($_POST["senha_usuario"]=="" && $_POST["confsenha_usuario"]=="")
				$this->errosForm["MENS_ERRO_SENHA"] = "A senha é um campo obrigatório";
			else if($_POST["senha_usuario"] != $_POST["confsenha_usuario"])
				$this->errosForm["MENS_ERRO_SENHA"] = "A senha deve ser igual à sua confirmação.";
			else
				$_POST["senha_usuario"] = base64_encode(md5($_POST["senha_usuario"]));
		}
	}
	
    /* METODOS GERAIS */
    
	function __construct(){
		global $objCtrlSmarty;
		confereSessao();
		setScriptMenu($this->menu1, $this->classe_css);
		$id = getId(); 
		$objCtrlSmarty->assign($this->PK,$id);
		$view = $_GET["a"];
		switch ($view){
			case 'form':
				self::getFormPadrao($id);
				break;
			case 'post':
				self::salvaDados($id);
				break;
			case 'excluir':
				self::getObjDaoPrincipal()->deletar($id);
				HttpUtil::vaiPara(HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=lista", "msg=4"));
				break;
			case 'lista':
			default:
				self::getListaDados();
				break;
		}
	}
	
	private function salvaDados(){
		global $menu;
		global $objCtrlSmarty;
		
		try{
			//validação caso o javascript esteja desabilitado
			$arrErros = array();
			foreach ($this->camposObrigatorios as $campo){
				//caso apresente erro já seto no template o erro.
				if($_POST[$campo[0]] == $campo[1]) $this->errosForm($campo[2],$campo[3]);
			}
			self::verificacoesExtras();
			//fim validação dos dados
			
			if(count($arrErros) == 0){
				$id = getId($_POST[$this->PK]);
				self::getObjDaoPrincipal()->alterar($id,$_POST,$_FILES);
				HttpUtil::vaiPara(HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=lista", "msg=3"));
			}else{
				//caso tenha algum erro exibo o form novamente apresentado o erro.
				self::getFormPadrao($id);
			}
		}catch(CustonException $e){
			HttpUtil::vaiPara(HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=lista", "msg=5"));
		}
	}
		
	private function getListaDados(){
		global $menu;
		global $objCtrlSmarty;
		
		$pagAtual = intval(FormataString::retiraCharsInvalidos(trim($_GET["pag"])));
		$ordenar = FormataString::retiraCharsInvalidos(trim($_GET["ord"]));
		self::getObjDaoPrincipal()->setCampoSessaoOrdenacao($this->classe_css);
		
		if(!empty($ordenar))
			$_SESSION["order_".$this->classe_css] = $ordenar;
		
		$arrDados = Utf8Parsers::matrizUtf8Encode(self::getObjDaoPrincipal()->getListaRegistros($pagAtual, addslashes($_POST["busca"])));
		$count = self::getObjDaoPrincipal()->getCountListaRegistros(addslashes($_POST["busca"]));
		
 		if ($count > NUM_ELEMENTOS_GRID) {
            $totPags = ceil($count / NUM_ELEMENTOS_GRID);
            $objCtrlSmarty->assign("NUMPAGS_GRID", $totPags);
            $objCtrlSmarty->assign("NUMREGS_GRID", $count);
            $objCtrlSmarty->assign("PAGATUAL_GRID", ($pagAtual +1));
            $objCtrlSmarty->assign("PAGINACAO", ($totPags > 1) ? true : false);
            $busca = (!empty($_POST["busca"]))?"busca=".addslashes($_POST["busca"]):"";
            $objCtrlSmarty->assign("LINK_ATUALPAG", HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=lista", $busca));
            $objCtrlSmarty->assign("LINK_PRIMEIRAPAG", HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=lista", $busca, "pag=nulo"));
            $objCtrlSmarty->assign("LINK_PAGANTERIOR", HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=lista", $busca, "pag=".($pagAtual-1)));
            $objCtrlSmarty->assign("LINK_PROXIMAPAG", HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=lista", $busca, "pag=".($pagAtual+1)));
            $objCtrlSmarty->assign("LINK_ULTIMAPAG", HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=lista", $busca, "pag=".($totPags-1)));
        }
		
		foreach ($arrDados as $key => $person){
        	$arrDados[$key]["editar"] = HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=form", "id=".$person[$this->PK]);
        	$arrDados[$key]["excluir"] = HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=excluir", "id=".$person[$this->PK]);
        }
        
        $arrOrder = array();
        foreach ($this->posArrGrid as $col){
        	$arrOrder[] = HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=lista", $busca, "ord=".$col);
        }
        $objCtrlSmarty->assign("POSITIONS_ORDER", $arrOrder);
        $objCtrlSmarty->assign("ORDERNAR_POR", $_SESSION["order_".$this->classe_css]);
        
        $objCtrlSmarty->assign("POSITIONS", $this->posGrid);
        $objCtrlSmarty->assign("POSITIONS_FIELDS", $this->posArrGrid);
        $objCtrlSmarty->assign("TITLE", $this->titleGrid);
        
        $objCtrlSmarty->assign("arrRegistros", $arrDados);
        $objCtrlSmarty->assign("TERMO_BUSCA", str_replace("\\\"", "&quot;", addslashes($_POST["busca"])));
        self::setLinksPadrao();
		$objCtrlSmarty->assign("CONTEUDO_ADMIN",$objCtrlSmarty->fetch(TPLS_FILE."admin/listaRegistros.tpl"));
	}
		
	private function getLinkCadastrar(){
		global $menu;
		return HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=form");
	}
		
	private function setLinksPadrao(){
		global $objCtrlSmarty;
		global $menu;
		
		$objCtrlSmarty->assign("LINK_BUSCAR", HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=lista"));
        $objCtrlSmarty->assign("LINK_CADASTRAR", self::getLinkCadastrar());
        $objCtrlSmarty->assign("LINK_ACTION", HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=post"));
		$objCtrlSmarty->assign("LINK_VOLTAR", HttpUtil::getLink($menu, "pos1=".__CLASS__));
	}
	
	private function getObjDaoPrincipal() {
        if ($this->objDaoPrincipal == null) {
            $this->objDaoPrincipal = new $this->DAO_principal();
        }
        return $this->objDaoPrincipal;
    }

}
?>